//
//  XTUserAccount.swift
//  HrenryWeibo
//
//  Created by 熊涛 on 16/5/13.
//  Copyright © 2016年 熊涛. All rights reserved.
//

import UIKit


//对象归档和解档
//1.在遵守NSCoding协议,要知道对象要保存和解档哪些属性
//2.滴啊用归档,解档方法

//用户账号
class XTUserAccount: NSObject,NSCoding {

    //MARK: - 属性
    
    //用户唯一的授权标志
    var access_token : String?
    //accsee_token的生命周期,单位是秒,基本数据类型不能使用? KVC会找不到
    var expires_in : NSTimeInterval = 0 {
        didSet {
            //KVC给expires_in赋值完后给expiresDate赋值
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //授权用户的UID
    var uid : String?
    
    //过期时间,方便比较
    var expiresDate : NSDate?
    
    //用户昵称
    var screen_name : String?
    
    //用户头像地址
    var avatar_large : String?
    
    
    //MARK: - method
    //字典转模型
    init(dict : [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    
    //setvalue:forkey:在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        XTPrint(items: "key : \(key)  value ; \(value)")
    }
    
    
    //打印方法
    override var description : String {
        get {
            return "用户账户:access_token : \(access_token), expires_in :\(expires_in), uid :\(uid), expiresDate : \(expiresDate), screen_name : \(screen_name), avatar_large : \(avatar_large)"
        }
    }
    
    
    //MARK: - 归档/解档
    //解档
    required init?(coder aDecoder: NSCoder) {
       access_token = aDecoder.decodeObjectForKey("access_token") as? String
       expires_in = aDecoder.decodeDoubleForKey("expires_in")
       uid = aDecoder.decodeObjectForKey("uid") as? String
       expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        
       screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
       avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    
    
}
